var sha1 = require('sha1')
var axios = require('axios')

var prefix = 'https://api.weixin.qq.com/cgi-bin/'
var api = {
  accessToken: prefix+'token?grant_type=client_credential'
}

function Wechat(opts){
  var that = this
  this.appID = opts.appID
  this.appSecret = opts.appSecret
  this.getAccessToken = opts.getAccessToken
  this.saveAccessToken = opts.saveAccessToken
  this.getAccessToken()
    .then(res => {
      console.log(res.toString())
      if(res.toString()){
        data = JSON.parse(res)
      }else{
        data = ''
      }
      
      if(that.isVaildAccessToken(data)){
        Promise.resolve(data)
      }else{
        console.log('到这里2'+data)
        return this.updateAccessToken()
      }
    }).then(res=>{
      this.access_token = res.access_token
      this.expires_in = res.expires_in
      this.saveAccessToken(res)
    }).catch(e=>{
      console.log(e)
      return this.updateAccessToken()
    })
}

Wechat.prototype.isVaildAccessToken = function(data){
  console.log('到这里'+data)
  if(!data || !data.access_token || !data.expires_in){
    return false
  }
  var access_token = data.access_token
  var expires_in = data.expires_in
  var now = +new Date()

  if(now < expires_in) {
    return true
  }else{
    return false
  }

}

Wechat.prototype.updateAccessToken = function(){
  var appID = this.appID
  var appSecret = this.appSecret
  var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret
  
  return new Promise((resolve, reject) => {
    axios.get(url).then(res => {
     
      var data = res.data
      var now = +new Date()
      console.log(data)
      var expires_in = now + (data.expires_in - 20)*1000
      data.expires_in = expires_in
      resolve(data)
    })
  })
  
}

module.exports = function (opts){
  var wechat = new Wechat(opts)
  return async function (ctx, next){
    console.log(ctx.query)
    var token = opts.token
    var signature = ctx.query.signature
    var nonce = ctx.query.nonce
    var timestamp = ctx.query.timestamp
    var echostr = ctx.query.echostr
  
    var str = [token, timestamp, nonce].sort().join('')
    var sha = sha1(str)
  
    if(sha === signature){
      ctx.body = echostr + ''
    }else{
      ctx.body = 'wrong'
    }
  }
}


